
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.border.TitledBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import jsyntaxpane.DefaultSyntaxKit;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLTreePanel extends JPanel {

	private JTree tree;
	private XMLTreeModel model;
	private JSplitPane splitPane;
	private JSplitPane splitPane2;
	private JButton saveButton;
	private JButton loadButton;
	private JEditorPane xmlEditorPane;

	private String xmlFilePath = "google_us.xml";
	private int pathCount;
	private XMLTreeFrame nf;

	public XMLTreePanel() {
		setLayout(new BorderLayout());
		// nf = new newFrame();

		model = new XMLTreeModel();
		tree = new JTree();
		TitledBorder leftBorder = BorderFactory
				.createTitledBorder("XML Viewer");
		leftBorder.setTitleJustification(TitledBorder.LEFT);
		TitledBorder leftBorder1 = BorderFactory
				.createTitledBorder("XML Editor");
		leftBorder1.setTitleJustification(TitledBorder.LEFT);
		tree.setModel(model);
		tree.setShowsRootHandles(true);
		tree.setEditable(false);

		xmlEditorPane = new JEditorPane();
		xmlEditorPane.setVisible(true);
		xmlEditorPane.setContentType("text/xml");
		saveButton = new JButton();
		saveButton.setVisible(false);
		saveButton.setText("Save Modified File");
		loadButton = new JButton();
		loadButton.setVisible(true);
		loadButton.setText("Load XML File");
		JPanel buttonPanel = new JPanel();
		buttonPanel.add(loadButton);
		buttonPanel.add(saveButton);

		JScrollPane xmlPane = new JScrollPane(tree);
		xmlPane.setBorder(leftBorder);
		JScrollPane textAreaPane = new JScrollPane(xmlEditorPane);
		textAreaPane.setBorder(leftBorder1);
		JScrollPane buttonPane = new JScrollPane(buttonPanel);

		DefaultSyntaxKit.initKit();
		splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, textAreaPane,
				buttonPane);
		splitPane2.setOneTouchExpandable(true);
		splitPane2.setDividerLocation(100);
		splitPane2.setPreferredSize(new Dimension(100, 100));
		splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, xmlPane,
				textAreaPane);
		splitPane.setOneTouchExpandable(true);
		splitPane.setDividerLocation(150);
		Dimension minSize = new Dimension(150, 200);
		xmlPane.setMinimumSize(minSize);
		textAreaPane.setMinimumSize(minSize);
		buttonPane.setMinimumSize(minSize);
		splitPane.setPreferredSize(new Dimension(400, 200));

		// pane.setPreferredSize(new Dimension(300,400));

		add(splitPane, "Center");
		add(splitPane2, "South");

		/*
		 * final JTextField text = new JTextField(); text.setEditable(false);
		 * add(text, "South");
		 */

		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {
				Object lpc = e.getPath().getLastPathComponent();
				Object lp = e.getPath();// .getParentPath();

				// Object child = model.getRoot();
				int lpcc = e.getPath().getPathCount();
				if (lpc instanceof XMLTreeNode) {


					// xmlTextData = xmlText.getText();

					pathCount = lpcc;

				}
			}

		});

		final JFileChooser loadLocationChooser = new JFileChooser();

		loadButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				FileFilter type1 = new ExtensionFilter("XML Source", ".xml");
				loadLocationChooser.addChoosableFileFilter(type1);
				int option = loadLocationChooser
						.showOpenDialog(XMLTreePanel.this);
				if (option == JFileChooser.APPROVE_OPTION) {
					if (loadLocationChooser.getSelectedFile() != null) {
						File theFileToSave = loadLocationChooser
								.getSelectedFile();

						try {
							refreshAction(theFileToSave);
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					}
				}
			}

		});
		final JFileChooser saveLocationChooser = new JFileChooser();

		saveButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				FileFilter type1 = new ExtensionFilter("XML source", ".xml");
				saveLocationChooser.addChoosableFileFilter(type1);
				int option = saveLocationChooser
						.showSaveDialog(XMLTreePanel.this);
				if (option == JFileChooser.APPROVE_OPTION) {
					if (saveLocationChooser.getSelectedFile() != null) {
						File theFileToSave = saveLocationChooser
								.getSelectedFile();
						try {
							saveAction1(theFileToSave);
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					}
				}
			}
		});

	}
	
	/*Method to save XML file after editing*/

	protected void saveAction1(File theFileToSave) throws IOException {
		// TODO Auto-generated method stub
		Writer out = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(theFileToSave), "UTF-8"));
		// FileOutputStream fop=new FileOutputStream(f);

		out.write(xmlEditorPane.getText());
		try {
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.close();

	}
	
	/*Method to load an xml file*/

	protected void refreshAction(File theFileToSave) throws Exception {
		// TODO Auto-generated method stub
		// model.setDocument(document);
		saveButton.setVisible(true);
		DocumentBuilderFactory docFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(theFileToSave);
		model.setDocument(doc);

		StringBuilder contents = new StringBuilder();

		try {
			BufferedReader in = new BufferedReader(
					new FileReader(theFileToSave));
			String str = null;
			while ((str = in.readLine()) != null) {
				contents.append(str);
				contents.append(System.getProperty("line.separator"));
			}
			// System.out.println(contents.toString());
			xmlEditorPane.setContentType("text/xml");
			xmlEditorPane.setText(contents.toString());

			in.close();
		} catch (IOException e) {
		}

	}



	/* methods that delegate to the custom model */
	public void setDocument(Document document) {
		model.setDocument(document);
	}

	public Document getDocument() {
		return model.getDocument();
	}

}
